package com.shop.cereshop.admin.controller.im;

import com.shop.cereshop.admin.service.im.ImService;
import com.shop.cereshop.commons.domain.im.tx.req.msg.MsgBody;
import com.shop.cereshop.commons.domain.im.tx.req.msg.UserSendMsgReq;
import com.shop.cereshop.commons.domain.im.tx.resp.ImBaseResp;
import com.shop.cereshop.commons.enums.RedisEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/imCallback")
@Api(tags = "用户消息回调")
@Slf4j
public class UserMsgCallBackController {
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ImService imService;

    @ApiOperation("收取用户消息回调")
    //https://www.example.com?SdkAppid=$SDKAppID&CallbackCommand=$CallbackCommand&contenttype=json&ClientIP=$ClientIP&OptPlatform=$OptPlatform
    @PostMapping("/callBack")
    public ImBaseResp callBack(@RequestBody UserSendMsgReq req, @RequestHeader(value = "SdkAppid", required = false) String sdkAppId, @RequestHeader(value = "CallbackCommand", required = false) String callbackCommand, @RequestHeader(value = "contenttype", required = false) String contentType, @RequestHeader(value = "ClientIP", required = false) String clientIP, @RequestHeader(value = "OptPlatform", required = false) String optPlatform) {
        log.info("打印请求参数 {}   {}", req, callbackCommand);
        String fromAccount = req.getFromAccount();
        Object member = redisTemplate.opsForHash().get(RedisEnum.MEMBER_USER_INFO.getKey(), fromAccount);
        ImBaseResp<MsgBody> resp = new ImBaseResp<>();
        resp.setActionStatus("OK");
        // 0 为允许发言  允许用户发言，同时也不变动即将下发的消息的内容。
        // 1 为拒绝发言 不允许用户发言，该消息将不会下发，同时给用户（即消息发送者）返回错误码20006。
        // 2 为静默丢弃 不允许用户发言，该消息将不会下发，但会给发送方返回成功，使发送方以为消息已经发出。
        if (member == null && !"administrator".equals(fromAccount)) {
            List<MsgBody> msgBodyList = new ArrayList<>();
            MsgBody msgBody = new MsgBody();
            msgBody.setMsgType("TIMTextElem");
            Map<String, String> msgContent = new HashMap<>();
            msgContent.put("Text", "当前未开通会员，请充值后进行沟通！");
            msgBody.setMsgContent(msgContent);
            msgBodyList.add(msgBody);
            // 非会员用户不允许发送消息，且管理员发送消息提示当前用户非管理员
            imService.sendMsg(fromAccount, msgBodyList);
            resp.setErrorCode(2);
        } else {
            resp.setErrorCode(0);
        }
        log.info("返回数据 {}", resp);
        return resp;
    }

}
